package com.example.rtm.busline;

import android.text.TextUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import okio.BufferedSource;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by RTM on 2017/9/25.
 */

public class NetworkRequest {
    private static OkHttpClient sClient;
    private static RxJavaCallAdapterFactory sRxJavaCallAdapterFactory = RxJavaCallAdapterFactory.create();
    private static GsonConverterFactory sGsonConverterFactory = GsonConverterFactory.create();

    static {
        sClient = obtainClient(20_000);
    }

    private static OkHttpClient obtainClient(long timeout) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(timeout, TimeUnit.MILLISECONDS);
        if (BuildConfig.DEBUG) {
            builder.addInterceptor(new OkHttpInterceptor());
        }
        return builder.build();
    }

    public static <T> T buildRequest(Class<T> cls) {
        return buildRequest(BuildConfig.BASE_URL, sClient, cls);
    }

    public static <T> T newRequest(Class<T> cls, long timeout) {
        return buildRequest(BuildConfig.BASE_URL, obtainClient(timeout), cls);
    }

    private static <T> T buildRequest(String baseUrl, OkHttpClient client, Class<T> cls) {
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(client)
                .addCallAdapterFactory(sRxJavaCallAdapterFactory)
                .addConverterFactory(sGsonConverterFactory)
                .build()
                .create(cls);
    }

    private static class OkHttpInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            long t1 = System.nanoTime();

            RequestBody body = request.body();
            Buffer requestBuffer = new Buffer();
            Charset charset = Charset.forName("UTF-8");
            if (body != null) {
                body.writeTo(requestBuffer);

            }

            Response response = chain.proceed(request);

            long t2 = System.nanoTime();


            try {
                BufferedSource source = response.body().source();
                source.request(Long.MAX_VALUE);
                Buffer buffer = source.buffer();


            } catch (Exception e) {
                e.printStackTrace();
            }

            return response;
        }

    }

}
